var c;
var $;
var w;
var h;

var floor;
var arr =[];
var re=8;

function Rain(x,y,vx,vy,speed,rcont,life,isreflect){
	this.set()
}

Rain.prototype={
	set(){
		this.y = -4.5;
		
		// this.x = Math.random() * window.innerWidth;
		this.x = Math.random() * c.width;
		this.vx = Math.random()>=0.5 ? 0.18: -0.18;
		this.vy = 0.2;
		this.speed = 0;
		this.rcount =8;
		this.life = Math.random()* 6000;
		this.isreflect = false;
	}
}

function upd(){
	for(var i in arr){
		arr[i].life--;
		if(arr[i].life <=0){
			if(arr[i].y > floor){
				if(arr[i].rcount==0){
					arr[i].y = floor;
				}
				else{
					let temp = arr[i].rcount -3;
					if(temp<0){
						temp = 1.8;
					}
					arr[i].isreflect = true;
					arr[i].speed = temp;
					arr[i].rcount -=1;
					arr[i].speed += arr[i].vy;
					arr[i].y += arr[i].speed;
					arr[i].x += arr[i].vx;
				}
			}else if(arr[i].y == floor){}
			else{
				if(arr[i].isreflect){
					arr[i].x += arr[i].vx;
				}
				arr[i].speed += arr[i].vy;
				arr[i].y += arr[i].speed;
			}
		}
		// if(arr[i].life <= -600 || arr[i].x < 0 || arr[i].x > window.innerWidth){
		// 	arr[i].set();
		// }
		if(arr[i].life <= -600 || arr[i].x < 0 || arr[i].x > c.width){
			arr[i].set();
		}
	}
}

function draw(){
	var p;
	$.fillStyle = "#ffffff";
	for	(var i in arr){
		p = arr[i];
		$.fillRect(p.x,p.y,2,2);
	}
}

function go(){
	for(var i =0;i<3600;i++){
		let d = new Rain();
		d.set;
		arr.push(d);
	}
}

function run(){
	$.clearRect(0,0,w,h);
	$.fillStyle = "#000000";
	$.fillRect(0,0,w,h);
	upd();
	draw();
	
	window.requestAnimationFrame(run);
	// requestAnimationFrame(run)
}

function resize(e){
	
	floor = h *1;
}

function initRain(cc,$$){
	c = cc; 
	$ = $$;
	//h5
	c.width = w = window.innerWidth;
	c.height = h = window.innerHeight;
	
	floor = h *1;
	// c.addEventListener('resize',resize(),false);
}

function startRain(){
	go();
	run();
}

function cancelRain(){
	arr = [] ;
	window.cancelAnimationFrame(run);
	// c.removeEventListener('resize',resize);
}

export {
	initRain,startRain,cancelRain
}